import { defineStore } from 'pinia'
export default defineStore('keepAlive',{
    state: () => {
        // const setMenu = new Set();
        return {
            keepAliveComponentsName: [],
            tabMenus: []
        }
    },
    getters:{
        keepAliveComponentsNames(state) {
            return state.keepAliveComponentsName
        },
        getTabMenusSize(state){
            return state.tabMenus.length
        }
    },
    actions:{
        // 重置，Push, splice keep-alive对象
        setKeepAliveComponentsName(nameArr) {
            this.keepAliveComponentsName = nameArr
        },
        addKeepAliveComponentsName(name) {
            this.keepAliveComponentsName.push(name)
        },
        delKeepAliveComponentsName(name) {
            const key = this.keepAliveComponentsName.indexOf(name)
            if (key !== -1) {
                this.keepAliveComponentsName.splice(key, 1)
                console.warn(this.keepAliveComponentsName)
            }
        },
        addTabs(menu){
            let isNotExist = true
            this.tabMenus.forEach(item=>{
                if (item.path === menu.path){
                    isNotExist = false
                }
            })
            if (this.tabMenus.length < 1 || isNotExist){
                this.tabMenus.push(menu)
            }
        },
        delTabs(menu){
          removeArray( this.tabMenus,menu)
        },
        resetTabs(menu){
            this.addTabs.splice(0,this.addTabs.length);
            this.addTabs(menu)
        }
    },persist: {
        enabled: true
    }
})

/**
 * 从数组中删除指定对象
 *  _arr:数组
 *  _obj:需删除的对象
 * */
function removeArray(_arr, _obj) {
    let length = _arr.length
    for (let i = 0; i < length; i++) {
        if (_arr[i] === _obj) {
            if (i === 0) {
                _arr.shift() //删除并返回数组的第一个元素
                return _arr
            } else if (i === length - 1) {
                _arr.pop()  //删除并返回数组的最后一个元素
                return _arr
            } else {
                _arr.splice(i, 1) //删除下标为i的元素
                return _arr
            }
        }
    }
}
